<template>
  <div class="slider" ref="slider">
		<!-- img -->
    <div class="slider-group" ref="sliderGroup">
    	<slot></slot>
    </div>
		<!-- dots -->
    <div class="dots">
    	  <span class="dot" 
					:class="{active: currentPageIndex === index }" 
					v-for="(item, index) in this.dots"  :key="index">
    		</span>
    </div>
  </div>
</template>

<script>
import {addClass} from 'common/js/dom'
import BScroll from 'better-scroll'
const COMPONENT_NAME = 'slide'
export default {
  name: COMPONENT_NAME,  
	data() {
      return {
        dots: [],
        currentPageIndex: 0
      }
	},
  props:{
    loop:{  // 循环轮播   
      type:Boolean,
      default:true
    },
    autoPlay:{//自动轮播
      type:Boolean,
      default:true
    },
    interval:{//轮播间隔
      type:Number,
      default:4000
    },
    showDot: { // 滚动点
        type: Boolean,
        default: true
      },
      click: {//点击
        type: Boolean,
        default: true
      },
      threshold: { //滑动的距离  阀值
        type: Number,
        default: 0.3
      },
      speed: { //滚动速度
        type: Number,
        default: 1200
      },
      pageTurn:{ //左右箭头  import SlideRender from 'example/page-render/slide-render.vue' @turnToPrevFun()

      }
  },
	mounted() {
		this.update()
		window.addEventListener('resize', () => { //监听改变窗口事件
			if (!this.slider || !this.slider.enabled) {
				return
			}
			clearTimeout(this.resizeTimer)
			this.resizeTimer = setTimeout(() => {
				if (this.slider.isInTransition) {
					this._onScrollEnd()
				} else {
					if (this.autoPlay) {
						this._play()
					}
				}
				this.refresh()
			}, 60)
		})
	},
	activated() {//https://blog.csdn.net/qq_24147051/article/details/81167093 生命周期图
		if (!this.slider) { //keep-alive组件激活时调用。 该钩子在服务器端渲染期间不被调用。
				return
			}
			this.slider.enable()
			let pageIndex = this.slider.getCurrentPage().pageX
			this.slider.goToPage(pageIndex, 0, 0)
			this.currentPageIndex = pageIndex
			if (this.autoPlay) {
				this._play()
		}
	},
	deactivated() {//keep-alive组件停用时调用。 该钩子在服务端渲染期间不被调用。 
		this.slider.disable()
		clearTimeout(this.timer)
	},
	beforeDestroy() {//销毁实例之前
		this.slider.disable()
		console.log("uuu")
		clearTimeout(this.timer)
	},
  methods: {
    update() { //当DOM发生改变的时候 调用
			if (this.slider) { //存在事件就销毁
				this.slide.destroy()
			}
			this.$nextTick(() => {
				this.init()
			})
		},
		refresh() {
			this._setSliderWidth(true)
			this.slider.refresh()
		},
		prev() {
			this.slider.prev()
		},
		next() {
			this.slider.next()
		},
		init() {//初始启动项
			clearTimeout(this.timer)
			this.currentPageIndex = 0
			this._setSliderWidth()
			if (this.showDot) {
				this._initDots() //循环小圆点事件
			}
			this._initSlider() //轮播图loop事件
			if (this.autoPlay) {
				this._play()   //触发下张轮播图事件
			}
		},
    _setSliderWidth(isResize){//计算轮播图宽度 给轮播图添加样式
			this.children=this.$refs.sliderGroup.children;//获取轮播图的子元素数组长度
			let width=0;
			let sliderWidth=this.$refs.slider.clientWidth//获取轮播图祖父元素的宽度=》只有子元素总长度大于父元素长度才可以滚动
			for (let index = 0; index < this.children.length; index++) {
					 const child = this.children[index];
					 addClass(child,"slider-item")//动态添加css样式
					 child.style.width=sliderWidth+"px"//设置子元素的宽度是父元素的100%
					 width+=sliderWidth//获取总长度
			}
		 if (this.loop && !isResize) {
				width += 2 * sliderWidth
			}
			this.$refs.sliderGroup.style.width=width+"px" //获取图片盒子的总宽度
    },
    _initSlider(){ //启动better-scroll插件 
			this.slider=new BScroll(this.$refs.slider,{
				scrollX: true,
				scrollY: false,
				momentum: false,//当快速在屏幕上滑动一段距离的时候，会根据滑动的距离和时间计算出动量，并生成滚动动画。设置为 true 则开启动画。
				snap: {
					loop: this.loop,//是否开启无缝轮播
					threshold: this.threshold,//滑动的距离
					speed: this.speed,//滚动速度
					interval:4000//轮播间隔
				},
				bounce: false,//当滚动超过边缘的时候会有一小段回弹动画。设置为 true 则开启
				stopPropagation: true,
				click: this.click,
				pageTurn:true
			}),
			this.slider.on('scrollEnd', () => { //滚动完毕触发事件index 
				let pageIndex = this.slider.getCurrentPage().pageX
				this.currentPageIndex = pageIndex
				if (this.autoPlay) { //无线滚动
					 this._play()
				}
			})
			this.slider.on('touchEnd', () => {
				if (this.autoPlay) {
					this._play()
				}
			})
			this.slider.on('beforeScrollStart', () => {
				if (this.autoPlay) {
					clearTimeout(this.timer)
				}
			})
    },
		_initDots() {//循环小圆点事件
			this.dots = new Array(this.children.length)
		},
		_play() { //触发下张轮播图事件
			clearTimeout(this.timer)
			this.timer = setTimeout(() => {
				this.slider.next()
			}, this.interval)
		}
  },
	watch: {
		loop() {
			this.update()
		},
		autoPlay() {
			this.update()
		},
		speed() {
			this.update()
		},
		threshold() {
			this.update()
		}
	},
}
</script>

<style lang="scss" scoped >
			.slider{
				min-height: 1px;
				@mixin bok{
					display: block;
					width: 100%;
				}
				.slider-group{
					position: relative;
					overflow: hidden;
					white-space: nowrap;
					.slider-item{
						float: left;
						box-sizing: border-box;
						overflow: hidden;
						text-align: center;
						a{
							@include bok();
							overflow: hidden;
							img{@include bok()}
						}
					}
				}
			  .dots{
					position: absolute;
					right: 0;
					left: 0;
					bottom: 12px;
					text-align: center;
					font-size: 0;
					.dot{
						display: inline-block;
						margin: 0 4px;
						width: 8px;
						height: 8px;
						border-radius:50%;
						background: $color-text-l;
						&.active{
							width: 20px;
							border-radius: 5px;
							background: $color-text-l;
						}
					}
				}
			
			}
</style>